package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.CustomException;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.Setmeal;
import com.reggie.mapper.CategoryMapper;
import com.reggie.service.CategoryService;
import com.reggie.service.DishService;
import com.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 分类删除
     * 若是已关联菜品或套餐则无法删除
     * @param id
     */
    @Override
    public void remove(Long id) {
        //查看菜品中是否关联了需要删除的分类id
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int dishCount = dishService.count(dishLambdaQueryWrapper);   //SQL:    select count(*) from dish where category_id=id;

        //查询结果大于0 则表示关联了菜品，抛出一个业务异常  否则表示没关联菜品
        if(dishCount>0){
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int setmealCount = setmealService.count(setmealLambdaQueryWrapper);  //SQL:    select count(*) from dish where category_id=id;

        //查询结果大于0 则表示关联了套餐，抛出一个业务异常  否则表示没关联套餐
        if(setmealCount>0){
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }

        //都没关联 正常删除
        super.removeById(id);
    }
}
